package com.xiaobai.service.quality;

import com.alibaba.fastjson.JSON;
import com.xiaobai.dao.QualityDao;
import com.xiaobai.units.HttpUnits;
import com.xiaobai.vo.AllQuality;
import com.xiaobai.vo.QualityItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QualityServiceImpl implements IQualityService{

    @Autowired
    private QualityDao qualityDao;

    private final String url="https://jwxt.gdupt.edu.cn/xsktsbxx!getYxktDataList.action";

    @Override
    public AllQuality allQualityJSON(String jsessionid, String student_id) {

        Map<String,String> map=new HashMap<>();

        map.put("page","1");
        map.put("rows","50");
        map.put("sort","cjsj");
        map.put("order","desc");

        String result=HttpUnits.gyPost(url,jsessionid,map);
//        String result="{\"total\":0,\"rows\":[]}";

        int startIndex=result.indexOf("\"rows\":")+7;
        int endIndex=result.length()-1;

        result=result.substring(startIndex,endIndex);

        List<String> listJSON= JSON.parseArray(result,String.class);

        AllQuality allQuality=new AllQuality();

        for(int i=0;i<listJSON.size();i++){
            QualityItem qualityItem=JSON.parseObject(listJSON.get(i),QualityItem.class);
            qualityItem.setKtmc(qualityItem.getKtmc().replaceAll("&ldquo;","\""));
            qualityItem.setKtmc(qualityItem.getKtmc().replaceAll("&rdquo;","\""));
            qualityItem.setKtmc(qualityItem.getKtmc().replaceAll("&middot;","-"));
            allQuality.getQualityItemList().add(qualityItem);
        }

        /**该存入数据库了
         */
        qualityDao.updateOrInsertQuality(student_id, JSON.toJSONString(allQuality.getQualityItemList()));

        return allQuality;
    }

    @Override
    public AllQuality allQualityJSONByDB(String student_id) {

        String dbValue=qualityDao.selectQualityByStudentId(student_id);

        List<String> list=JSON.parseArray(dbValue,String.class);

        List<QualityItem> qualityItems=new ArrayList<>();

        for(int i=0;i<list.size();i++){
            qualityItems.add(JSON.parseObject(list.get(i),QualityItem.class));
        }

        AllQuality allQuality=new AllQuality();

        allQuality.setQualityItemList(qualityItems);

        return allQuality;
    }
}
